package stepdefinations;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

import selenium.SeleniumBase;
import cucumber.api.DataTable;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

/**
 * @author Pallavi verifying headers and footers of nopcommerce page
 */

public class SmokeStepDinations extends SeleniumBase{
	

	@Before
	public void openBrowser() {
		driver = new FirefoxDriver();
		// System.setProperty("webdriver.chrome.driver",
		// "C:\\chrome&IE\\chromedriver.exe");
		// driver = new ChromeDriver();
		// System.setProperty("webdriver.ie.driver",
		// "C:\\chrome&IE\\IEDriverServer.exe");
		// driver = new InternetExplorerDriver();
	}

	@Given("^user navigates to \"(.*?)\"$")
	public void navigateTo(String url) throws Throwable {

		Assert.assertEquals("nopCommerce demo store", navigateToHomePage(url));
	}

	@Given("^As a user verifying navigation to Register,Login,SHopingCart,WihList Pages$")
	public void navigatingToHeaderLinks() throws Throwable {

		Assert.assertTrue(isHeaderLinksVisible());
	}

	@Given("^As a user verifying navigation to Sitemap,Shipping & Returns,Privacy Notice,Conditions of Use,About us,Contact us$")
	public void navigatingToFooterLinks() throws Throwable {
		Assert.assertTrue(isFooterLinksNavigated());

	}

	@Given("^As a user verifying navigation to Search,News,Blog,Recently viewed products,Compare products list,New products$")
	public void navigatingToCustomerServiceFooterLinks() throws Throwable {
		Assert.assertTrue(isCustomerServiceFooterLinks());
	}

	@Given("^As a user verifying navigation to My account,Orders,Addresses,Shopping cart,Wishlist$")
	public void navigatingToMyAccountFooterLinks() throws Throwable {
		Assert.assertTrue(isMyAccountFooterLinks());
	}

	@Given("^As a user verifying navigation to Facebook,Twitter,RSS,YouTube,Google\\+$")
	public void navigatingToFollowUsFooterLinks() throws Throwable {
		Assert.assertTrue(isFollowUs());
	}

	@Given("^As a user verifying navigation to ASUS,HP$")
	public void navigatingToManufacturersLinks() throws Throwable {
	}

	@When("^user clicks on register link$")
	public void userclicksonregisterlink() throws Throwable {

		Assert.assertTrue(VerifyUserCanClickOnRegisterLink());
	}

	@Then("^check page title \"(.*?)\"$")
	public void checkpagetitle(String pagetitle) throws Throwable {
		Assert.assertEquals(pagetitle, driver.getTitle());
	}

	@Then("^select radio button$")
	public void select_radio_button() throws Throwable {
		Assert.assertTrue(VerifyUserCanSelectRadioButton());

	}

	@Given("^fill textbox:$")
	public void fill_textbox(List<String> results) throws Throwable {
		Assert.assertTrue(verifyingTextboxVisible(results));

	}

	@Then("^select Date of birth \"(.*?)\",\"(.*?)\",\"(.*?)\"$")
	public void select_Date_of_birth(String Date, String Month, String Year)
			throws Throwable {
		Assert.assertTrue(isverifyDropdownList(Date, Month, Year));
	}

	@Then("^tick \"(.*?)\"$")
	public void tick(String newsletter) throws Throwable {
		Assert.assertTrue(isnewslettercheckboxvisible(newsletter));

	}

	@Then("^click on \"(.*?)\"$")
	public void clickon(String registerbutton) throws Throwable {
		Assert.assertTrue(isregisterbuttonvisible(registerbutton));

	}

	@Then("^user navigates to register cofirmation page$")
	public void usernavigatestoregistercofirmationpage() throws Throwable {
		Assert.assertTrue(islogoutlinkdisplayed());

	}

	private boolean islogoutlinkdisplayed() {
		if (driver.findElement(By.className("ico-logout")).isDisplayed()) {
			driver.findElement(By.className("ico-logout")).click();
			return true;
		}
		return false;

	}

	private String randomEmail(int length) {
		String allowedChars = "abcdefghijklmnopqrstuvwxyz" + // alphabets
				"1234567890"; // numbers

		String email = "";
		String temp = RandomStringUtils.random(length, allowedChars);
		email = temp + "@test.gmail.com";
		return email;
	}

	public String navigateToHomePage(String url) {
		driver.navigate().to(url);
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
		return driver.getTitle();
	}

	private boolean isHeaderLinksVisible() {

		String[] pageTitle = { "nopCommerce demo store. Register",
				"nopCommerce demo store. Login",
				"nopCommerce demo store. Shopping Cart",
				"nopCommerce demo store. Wishlist" };

		String links[] = { "ico-register", "ico-login", "cart-label",
				"ico-wishlist" };

		for (int i = 0; i < links.length; i++) {

			if (driver.findElement(By.className(links[i])).isDisplayed()) {
				driver.findElement(By.className(links[i])).click();
				driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
				Assert.assertEquals(pageTitle[i], driver.getTitle());
				driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
				driver.findElement(
						By.cssSelector("img[alt='nopCommerce demo store']"))
						.click();
				Assert.assertEquals("nopCommerce demo store", driver.getTitle());
			}
		}

		return true;

	}

	private boolean isFooterLinksNavigated() {
		JavascriptExecutor jse = (JavascriptExecutor) driver;
		jse.executeScript("scroll(0, 500);");
		String[] pageTitle = { "nopCommerce demo store. Sitemap",
				"nopCommerce demo store. Shipping & Returns",
				"nopCommerce demo store. Privacy policy",
				"nopCommerce demo store. Conditions of use",
				"nopCommerce demo store. About Us",
				"nopCommerce demo store. Contact Us" };
		String links[] = { "Sitemap", "Shipping & Returns", "Privacy Notice",
				"Conditions of Use", "About us", "Contact us" };
		driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
		for (int i = 0; i < links.length; i++) {
			if (driver.findElement(By.partialLinkText(links[i])).isDisplayed()) {
				driver.findElement(By.partialLinkText(links[i])).click();
				Assert.assertEquals(pageTitle[i], driver.getTitle());
				driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
				driver.findElement(
						By.cssSelector("img[alt='nopCommerce demo store']"))
						.click();
				Assert.assertEquals("nopCommerce demo store", driver.getTitle());

			}
		}

		return true;
	}

	private boolean isCustomerServiceFooterLinks() {
		JavascriptExecutor jse = (JavascriptExecutor) driver;
		jse.executeScript("scroll(0, 500);");
		String[] pageTitle = { "nopCommerce demo store. Search",
				"nopCommerce demo store. News Archive",
				"nopCommerce demo store. Blog",
				"nopCommerce demo store. Recently Viewed Products",
				"nopCommerce demo store. Compare Products",
				"nopCommerce demo store. Recently Added Products" };
		String links[] = { "Search", "News", "Blog",
				"Recently viewed products", "Compare products list",
				"New products" };
		driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
		for (int i = 0; i < links.length; i++) {
			if (driver.findElement(By.linkText(links[i])).isDisplayed()) {
				driver.findElement(By.partialLinkText(links[i])).click();
				Assert.assertEquals(pageTitle[i], driver.getTitle());
				driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
				driver.findElement(
						By.cssSelector("img[alt='nopCommerce demo store']"))
						.click();
				Assert.assertEquals("nopCommerce demo store", driver.getTitle());

			}
		}

		return true;
	}

	private boolean isMyAccountFooterLinks() {
		JavascriptExecutor jse = (JavascriptExecutor) driver;
		jse.executeScript("scroll(0, 500);");
		String[] pageTitle = { "nopCommerce demo store. Login",
				"nopCommerce demo store. Login",
				"nopCommerce demo store. Login",
				"nopCommerce demo store. Shopping Cart",
				"nopCommerce demo store. Wishlist" };
		String links[] = { "My account", "Orders", "Addresses",
				"Shopping cart", "Wishlist" };
		driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
		for (int i = 0; i < links.length; i++) {
			driver.findElement(By.partialLinkText(links[i])).click();
			Assert.assertEquals(pageTitle[i], driver.getTitle());
			driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
			driver.findElement(
					By.cssSelector("img[alt='nopCommerce demo store']"))
					.click();
			Assert.assertEquals("nopCommerce demo store", driver.getTitle());

		}
		return true;
	}

	private boolean isFollowUs() {
		JavascriptExecutor jse = (JavascriptExecutor) driver;
		jse.executeScript("scroll(0, 500);");

		String[] pageTitle = { "NopCommerce | Facebook",
				"nopCommerce (@nopCommerce) | Twitter",
				"nopCommerce demo store: News", "nopCommerce - YouTube",
				"nopCommerce - Google+" };
		String links[] = { "Facebook", "Twitter", "RSS", "YouTube", "Google+" };

		String winHandleBefore = driver.getWindowHandle();
		driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
		for (int i = 0; i < links.length; i++) {
			driver.findElement(By.partialLinkText(links[i])).click();
			driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
			for (String winHandle : driver.getWindowHandles()) {
				driver.switchTo().window(winHandle);

			}
			Assert.assertEquals(pageTitle[i], driver.getTitle());
			if (links[i].equalsIgnoreCase("RSS")) {
				driver.navigate().back();
				Assert.assertEquals("nopCommerce demo store", driver.getTitle());
			} else {
				driver.close();
				driver.switchTo().window(winHandleBefore);
			}

			driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
			driver.findElement(
					By.cssSelector("img[alt='nopCommerce demo store']"))
					.click();
			Assert.assertEquals("nopCommerce demo store", driver.getTitle());
		}
		return true;

	}

	private boolean VerifyUserCanSelectRadioButton() {
		if (!driver.findElement(By.id("gender-male")).isSelected()) {
			driver.findElement(By.id("gender-male")).click();
			return true;
		}
		return false;
	}

	private boolean verifyingTextboxVisible(List<String> results) {
		try {
			for (String element : results) {
				if (element.equalsIgnoreCase("Email")) {
					driver.findElement(By.id(element))
							.sendKeys(randomEmail(10));
				} else if (element.equalsIgnoreCase("Password")
						|| element.equalsIgnoreCase("ConfirmPassword")) {
					driver.findElement(By.id(element)).sendKeys("aaaaaa");
				} else {
					driver.findElement(By.id(element)).sendKeys(
							RandomStringUtils.random(10,
									"abcdefghijklmnopqrstuvwxyz"));
				}
			}
			return true;

		} catch (NoSuchElementException e) {
			e.printStackTrace();
		}
		return false;

	}

	private boolean VerifyUserCanClickOnRegisterLink() {
		driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
		if (driver.findElement(By.className("ico-register")).isDisplayed()) {
			driver.findElement(By.className("ico-register")).click();
			return true;
		}
		return false;
	}

	private boolean isverifyDropdownList(String date, String month, String year) {
		try {
			driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
			if (driver.findElement(By.name("DateOfBirthDay")).isDisplayed()
					&& driver.findElement(By.name("DateOfBirthMonth"))
							.isDisplayed()
					&& driver.findElement(By.name("DateOfBirthYear"))
							.isDisplayed()) {
				Select dropdown = new Select(driver.findElement(By
						.name("DateOfBirthDay")));
				dropdown.selectByValue(date);
				Select dropdown1 = new Select(driver.findElement(By
						.name("DateOfBirthMonth")));
				dropdown1.selectByValue(month);
				Select dropdown2 = new Select(driver.findElement(By
						.name("DateOfBirthYear")));
				dropdown2.selectByValue(year);
			}
			return true;

		} catch (NoSuchElementException e) {
			e.printStackTrace();
		}

		return false;

	}

	private boolean isnewslettercheckboxvisible(String newsletter) {
		if (!driver.findElement(By.id(newsletter)).isEnabled()) {
			driver.findElement(By.id(newsletter)).click();
		}
		return true;
	}

	private boolean isregisterbuttonvisible(String registerbutton) {
		if (driver.findElement(By.id(registerbutton)).isDisplayed()) {
			driver.findElement(By.id(registerbutton)).click();
			driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
		}
		return true;
	}
	
	@After
	public void closeBrowser() {
		driver.close();
	}

}
